package br.pucrio.inf.aaaong.models.database.update;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import br.pucrio.inf.aaaong.models.database.exceptions.PostgreSQLConstraintException;
import br.pucrio.inf.aaaong.utils.ExceptionLogger;

public class UpdateQueryExecutor {
	private Connection connection;
	
	public UpdateQueryExecutor(Connection connection) {
		this.connection = connection;
	}

	public void execute(String query,
			UpdateQueryParamsPreparer updateQueryParamsPreparer) throws PostgreSQLConstraintException {
		PreparedStatement ps;
		try {
			ps = connection.prepareStatement(query);
		} catch (SQLException e1) {
			e1.printStackTrace();
			throw new RuntimeException("Invalid update query.");
		}
		
		try {
			updateQueryParamsPreparer.prepareParameters(new UpdateQueryParamsSetter(ps));
		} catch (SQLException e1) {
			e1.printStackTrace();
			throw new RuntimeException("Error setting update parameters.");
		}
		
		try {
			ps.executeUpdate();
		} catch (SQLException e) {
			if (PostgreSQLConstraintException
					.isConstraintViolationCode(e.getSQLState())) {
				throw PostgreSQLConstraintException
					.fromExceptionMessage(e.getMessage());
			} else {
				ExceptionLogger.log(e);
				throw new RuntimeException("SQL: error on update execution");
			}
		}
	}

}
